package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.entity.User;
import com.ruoyi.livedemo.entity.UserSession;
import com.ruoyi.livedemo.mapper.UserMapper;
import com.ruoyi.livedemo.mapper.UserSessionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
@RequiredArgsConstructor
// TokenService 负责管理用户登录会话令牌，封装签发、校验与失效逻辑
public class TokenService {

    private final UserSessionMapper sessionMapper;
    private final UserMapper userMapper;

    @Value("${app.security.token.expire-hours:24}")
    private long expireHours;

    @Transactional
    public String issueToken(User user, String userAgent) {
        sessionMapper.deleteExpired(LocalDateTime.now());
        UserSession session = new UserSession();
        session.setUserId(user.getId());
        session.setToken(UUID.randomUUID().toString());
        session.setIssuedAt(LocalDateTime.now());
        session.setExpiresAt(LocalDateTime.now().plusHours(expireHours));
        session.setUserAgent(userAgent);
        sessionMapper.insert(session);
        return session.getToken();
    }

    public User validateToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            return null;
        }
        UserSession session = sessionMapper.findByToken(token);
        if (session == null) {
            return null;
        }
        if (session.getExpiresAt() != null && session.getExpiresAt().isBefore(LocalDateTime.now())) {
            sessionMapper.deleteByToken(token);
            return null;
        }
        return userMapper.findById(session.getUserId());
    }

    public void invalidate(String token) {
        if (token != null && !token.trim().isEmpty()) {
            sessionMapper.deleteByToken(token);
        }
    }

    public long getExpireHours() {
        return expireHours;
    }
}
